package com.sxt.sys.service.impl;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxt.sys.common.*;
import com.sxt.sys.domain.Dept;
import com.sxt.sys.domain.Role;
import com.sxt.sys.service.DeptService;
import com.sxt.sys.service.RoleService;
import com.sxt.sys.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxt.sys.domain.User;
import com.sxt.sys.mapper.RoleMapper;
import com.sxt.sys.mapper.UserMapper;
import com.sxt.sys.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 老雷
 * @since 2019-09-20
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Override
	public boolean save(User entity) {
		return super.save(entity);
	}
	
	@Override
	public boolean updateById(User entity) {
		return super.updateById(entity);
	}
	
	@Override
	public User getById(Serializable id) {
		return super.getById(id);
	}
	
	@Override
	public boolean removeById(Serializable id) {
		//根据用户ID删除用户角色中间表的数据
		roleMapper.deleteRoleUserByUid(id);
		//删除用户头[如果是默认头像不删除  否则删除]
		return super.removeById(id);
	}

	@Override
	public void saveUserRole(Integer uid, Integer[] ids) {
		//根据用户ID删除sys_role_user里面的数据
		roleMapper.deleteRoleUserByUid(uid);
		if(null!=ids&&ids.length>0) {
			for (Integer rid : ids) {
				roleMapper.insertUserRole(uid,rid);
			}
		}
	}

	//=======================================================================================================


	@Autowired
	private DeptService deptService;

	@Autowired
	private RoleService roleService;

	/**
	 * 用户全查询
	 */
	public List<User> loadAllUser(UserVo userVo) {
		IPage<User> page=new Page<>(userVo.getPage(), userVo.getLimit());
		QueryWrapper<User> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq(StringUtils.isNotBlank(userVo.getName()), "loginname", userVo.getName()).or().eq(StringUtils.isNotBlank(userVo.getName()), "name", userVo.getName());
		queryWrapper.eq(StringUtils.isNotBlank(userVo.getAddress()), "address", userVo.getAddress());
		queryWrapper.eq("type", Constast.USER_TYPE_NORMAL);//查询系统用户
		queryWrapper.eq(userVo.getDeptid()!=null, "deptid",userVo.getDeptid());
		this.page(page, queryWrapper);
		List<User> list = page.getRecords();
		for (User user : list) {
			Integer deptid = user.getDeptid();
			if(deptid!=null) {
				Dept one =deptService.getById(deptid);
				user.setDeptname(one.getTitle());
			}
			Integer mgr = user.getMgr();
			if(mgr!=null) {
				User one = this.getById(mgr);
				user.setLeadername(one.getName());
			}
		}
		return list;
	}



	/**
	 * 加载最大的排序码
	 * @param
	 * @return
	 */
	public List<User> loadUserMaxOrderNum(){
		QueryWrapper<User> queryWrapper=new QueryWrapper<>();
		queryWrapper.orderByDesc("ordernum");
		IPage<User> page=new Page<>(1, 1);
		List<User> list = this.page(page, queryWrapper).getRecords();
		return list;
	}


	/**
	 * 根据部门ID查询用户
	 */
	public List<User> loadUsersByDeptId(Integer deptid) {
		QueryWrapper<User> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq(deptid!=null, "deptid", deptid);
		queryWrapper.eq("available", Constast.AVAILABLE_TRUE);
		queryWrapper.eq("type", Constast.USER_TYPE_NORMAL);
		List<User> list = this.list(queryWrapper);
		return list;
	}



	/**
	 * 添加用户
	 */
	public Boolean addUser(UserVo userVo) {
		try {
			userVo.setType(Constast.USER_TYPE_NORMAL);//设置类型
			userVo.setHiredate(new Date());
			String salt= IdUtil.simpleUUID().toUpperCase();
			userVo.setSalt(salt);//设置盐
			userVo.setPwd(new Md5Hash(Constast.USER_DEFAULT_PWD, salt, 2).toString());//设置密码
			this.save(userVo);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}




	/**
	 * 修改用户
	 */
	public Boolean updateUser(UserVo userVo) {
		try {
			this.updateById(userVo);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 删除用户
	 */
	public Boolean deleteUser(Integer id) {
		try {
			this.removeById(id);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 重置用户密码
	 */
	public Boolean resetPwd(Integer id) {
		try {
			User user=new User();
			user.setId(id);
			String salt=IdUtil.simpleUUID().toUpperCase();
			user.setSalt(salt);//设置盐
			user.setPwd(new Md5Hash(Constast.USER_DEFAULT_PWD, salt, 2).toString());//设置密码
			this.updateById(user);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}


	/**
	 * 根据用户ID查询角色并选中已拥有的角色
	 */
	public List<Map<String, Object>> initRoleByUserId(Integer id) {
		//1,查询所有可用的角色
		QueryWrapper<Role> queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("available", Constast.AVAILABLE_TRUE);
		List<Map<String, Object>> listMaps = this.roleService.listMaps(queryWrapper);

		//2,查询当前用户拥有的角色ID集合
		List<Integer> currentUserRoleIds=this.roleService.queryUserRoleIdsByUid(id);
		for (Map<String, Object> map : listMaps) {
			Boolean LAY_CHECKED=false;
			Integer roleId=(Integer) map.get("id");
			for (Integer rid : currentUserRoleIds) {
				if(rid==roleId) {
					LAY_CHECKED=true;
					break;
				}
			}
			map.put("LAY_CHECKED", LAY_CHECKED);
		}
		return listMaps;
	}


	/**
	 * 用户修改密码
	 */
	public Boolean udpatepwd(String newpwd){
		try {
			User user = (User) WebUtils.getSession().getAttribute("user");
			user.setPwd(new Md5Hash(newpwd,user.getSalt(), 2).toString());//设置密码
			this.updateById(user);
			WebUtils.getSession().removeAttribute("user");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public User getOneRealm(AuthenticationToken token) {
		QueryWrapper<User> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("loginname", token.getPrincipal().toString());
		return this.getOne(queryWrapper);
	}

}
